<?php
namespace App\Http\Controllers\Api\Buz;

use App\Http\Controllers\Controller;
use App\Lib\Code;
use App\Repositories\Criteria\AuthUserCriteria;
use App\Repositories\Eloquent\RechargeOrderRepository;
use App\Services\ApiResponseService;
use App\Services\RechargeOrderNotifyService;
use Illuminate\Http\Request;

class RechargeOrderController extends Controller
{
    protected $orderRepository;

    public function __construct(RechargeOrderRepository $rechargeOrderRepository)
    {
        $this->orderRepository = $rechargeOrderRepository;
        $this->orderRepository->pushCriteria(AuthUserCriteria::class);
    }

    public function show(Request $request, $id)
    {
        $order = $this->orderRepository->with(['notify' => function ($query) {
            $query->select('order_id', 'notify_time', 'handle_time', 'status', 'res_content', 'updated_at');
        }])->find($id,
            [
                'id', 'plat_no', 'merchant_no', 'order_amt',
                'order_status', 'order_settle', 'req_ip',
                'created_at', 'updated_at', 'is_settle',
                'settled_at', 'settle_day'
            ]);
        return ApiResponseService::returnData($order);
    }

    public function callback(RechargeOrderNotifyService $rechargeOrderNotifyService, $id)
    {
        $order = $this->orderRepository->findWhere(['order_status' => 1, 'id' => $id])->first();
        if ( ! $order) {
            return ApiResponseService::showError(Code::NOTFOUND);
        }
        $res = $rechargeOrderNotifyService->curlRequest($order->notify, 'post', true, true);
        $notify = $res['rechargeOrderNotify'];
        array_forget($notify, [
            'id', 'order_id', 'res_status',
            'res_content', 'status', 'notified_at',
            'created_at', 'updated_at', 'notify_time'
        ]);
        $res['rechargeOrderNotify'] = $notify;
        unset($notify);
        return ApiResponseService::returnData($res);
    }

}
